<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import { marked } from 'marked';
import txt from '../../../../../../README.md?raw';
import xss from 'xss';

marked.setOptions({
    breaks: true, // 识别换行符
    gfm: true,
    pedantic: false,
});
const mdStr = txt as string;
onMounted(() => {
    speak(mdStr);
});

let timer: number | NodeJS.Timeout;
const htmlStr = ref('');
const speak = (md: string) => {
    const lines = md.split('\n');

    let index = 0;
    const nextWord = () => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            // + '|' 是为了做光标
            index++;
            const str = lines.slice(0, index).join('');
            console.log(str);
            htmlStr.value = mdToHtml(str);

            // 等 htmlStr 在页面上渲染出来
            nextTick(() => {
                if (index === lines.length) {
                    return;
                }
                nextWord();
            });
        }, Math.random() * 100);
    };
    nextWord();
};

const mdToHtml = (md: string) => {
    return marked.parse(md) as string;
};
</script>

<template>
    <div class="using" ref="using" v-html="xss(htmlStr)"></div>
</template>

<style scoped lang="scss">
.using {
    height: 400px;
    overflow-y: auto;
}
</style>
